package com.cal2sync;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.android.internal.telephony.ITelephony;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.widget.Toast;

public class GetCalendarEvents extends Service{

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	 public void onStart(Intent intent, int startId) {
	  // TODO Auto-generated method stub
	  super.onStart(intent, startId);
	  
	  Toast.makeText(GetCalendarEvents.this, "Inside service", Toast.LENGTH_LONG).show();

	  ContentResolver contentResolver = GetCalendarEvents.this.getContentResolver();

		// Fetch a list of all calendars synced with the device, their display names and whether the
		// user has them selected for display.

		final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),
				(new String[] { "_id", "displayName", "selected" }), null, null, null);
		// For a full list of available columns see http://tinyurl.com/yfbg76w

		HashSet<String> calendarIds = new HashSet<String>();
		if(cursor.getCount()!= 0){
			while (cursor.moveToNext()) {

				final String _id = cursor.getString(0);
				final String displayName = cursor.getString(1);
				final Boolean selected = !cursor.getString(2).equals("0");

				System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
				calendarIds.add(_id);
			}
		}
		// For each calendar, display all the events from the previous week to the end of next week.		
		for (String id : calendarIds) {
			Uri.Builder builder = Uri.parse("content://calendar/instances/when").buildUpon();
			long now = new Date().getTime();
			ContentUris.appendId(builder, now - DateUtils.WEEK_IN_MILLIS);
			ContentUris.appendId(builder, now + DateUtils.WEEK_IN_MILLIS);
			Date currentEndTime = new Date();
			Cursor eventCursor = contentResolver.query(builder.build(),
					new String[] { "title", "begin", "end", "allDay","description","eventLocation"}, "Calendars._id=" + id,
					null, "startDay ASC, startMinute ASC"); 
			// For a full list of available columns see http://tinyurl.com/yfbg76w
			if(eventCursor.getCount()!= 0){

				eventCursor.moveToFirst();			
				do{
					String title = eventCursor.getString(0);
					if(title.contains("Meeting")||title.contains("meeting")||title.contains("Interview")||title.contains("interview"))
						title="Meeting";
					else if(title.contains("Party")||title.contains("party")||title.contains("Birthday")||title.contains("birthday"))
						title="Party";
					else if(title.contains("Recreation")||title.contains("recreation")||title.contains("Movie")||title.contains("movie"))
						title="Recreation";
					else if(title.contains("Work")||title.contains("work")||title.contains("careerfair")||title.contains("Careerfair")||title.contains("Job")||title.contains("job"))
						title="Work";
					else if(title.contains("Family/Friends")||title.contains("family/friends")||title.contains("Dinner")||title.contains("dinner")||title.contains("Lunch")||title.contains("lunch"))
						title="Family/Friends";
					
					
					final Date begin = new Date(eventCursor.getLong(1));
					final Date end = new Date(eventCursor.getLong(2));
					final Boolean allDay = !eventCursor.getString(3).equals("0");
					StringBuilder builder1 = new StringBuilder();

					System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
							" All Day: " + allDay);
					//Getting the events and checking if they fall in the current time zone
					Date currentDate = new Date();
					String currentRule = new String();
					if(currentDate.after(begin) && currentDate.before(end)){
						GlobalData.currentRuleendTime=end;
						//rules: silent,vibrate,ringtone,voicemail

						HttpClient httpclient = new DefaultHttpClient();
						//HttpPost httppost = new HttpPost("http://10.0.2.2/select_rules.php");
						HttpPost httppost = new HttpPost("http://192.168.16.1/select_rules.php");
						HttpResponse response = null;
						try {
							// Add your data
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
							nameValuePairs.add(new BasicNameValuePair("username", GlobalData.username));
							nameValuePairs.add(new BasicNameValuePair("event_type", title));
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

							// Execute HTTP Post Request
							response = httpclient.execute(httppost);
							Reader in = new BufferedReader(
							        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
							    //builder1= new StringBuilder();
							    char[] buf = new char[1000];
							    int l = 0;
							    while (l >= 0) {
							        builder1.append(buf, 0, l);
							        l = in.read(buf);
							    }
							System.out.println("Response ->"+builder1.toString());

						} catch (ClientProtocolException e) {
							System.out.println("exception 1");
							// TODO Auto-generated catch block
						} catch (IOException e) {
							e.printStackTrace();
							System.out.println("error ");
							// TODO Auto-generated catch block
						}
						if(builder1.toString().equals("Silent"))
						{
							AudioManager am = (AudioManager) GetCalendarEvents.this.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
						}
						else if(builder1.toString().equals("Vibrate"))
						{
							AudioManager am = (AudioManager) GetCalendarEvents.this.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
						}
						else if(builder1.toString().equals("Voicemail"))
						{
							AudioManager am = (AudioManager) GetCalendarEvents.this.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
							GlobalData.flag=true;
						}

					}
					else   // if current event time is not satisfied
					{
						if(GlobalData.currentRuleendTime!=null)
						{
							if(currentDate.after(GlobalData.currentRuleendTime))  // if time of previous event is done then change to ringtone
							{
								GlobalData.flag=false;
								AudioManager am = (AudioManager) GetCalendarEvents.this.getSystemService(Context.AUDIO_SERVICE);
								am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
							}
						}
					}
				}while (eventCursor.moveToNext());
			}
		}
	}

	/*public static void getCalendarEvents(Context context){
		ContentResolver contentResolver = context.getContentResolver();

		// Fetch a list of all calendars synced with the device, their display names and whether the
		// user has them selected for display.

		final Cursor cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
				(new String[] { "_id", "displayName", "selected" }), null, null, null);
		// For a full list of available columns see http://tinyurl.com/yfbg76w

		HashSet<String> calendarIds = new HashSet<String>();
		if(cursor.getCount()!= 0){
			while (cursor.moveToNext()) {

				final String _id = cursor.getString(0);
				final String displayName = cursor.getString(1);
				final Boolean selected = !cursor.getString(2).equals("0");

				System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
				calendarIds.add(_id);
			}
		}
		// For each calendar, display all the events from the previous week to the end of next week.		
		for (String id : calendarIds) {
			Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
			long now = new Date().getTime();
			ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS);
			ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS);
			Date currentEndTime = new Date();
			Cursor eventCursor = contentResolver.query(builder.build(),
					new String[] { "title", "begin", "end", "allDay","description","eventLocation"}, "Calendars._id=" + id,
					null, "startDay ASC, startMinute ASC"); 
			// For a full list of available columns see http://tinyurl.com/yfbg76w
			if(eventCursor.getCount()!= 0){

				eventCursor.moveToFirst();			
				do{
					final String title = eventCursor.getString(0);
					final Date begin = new Date(eventCursor.getLong(1));
					final Date end = new Date(eventCursor.getLong(2));
					final Boolean allDay = !eventCursor.getString(3).equals("0");
					StringBuilder builder1 = new StringBuilder();

					System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
							" All Day: " + allDay);
					//Getting the events and checking if they fall in the current time zone
					Date currentDate = new Date();
					String currentRule = new String();
					if(currentDate.after(begin) && currentDate.before(end)){
						GlobalData.currentRuleendTime=end;
						//rules: silent,vibrate,ringtone,voicemail

						HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost("http://10.0.2.2/select_rules.php");
						HttpResponse response = null;
						try {
							// Add your data
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
							nameValuePairs.add(new BasicNameValuePair("username", GlobalData.username));
							nameValuePairs.add(new BasicNameValuePair("event_type", title));
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

							// Execute HTTP Post Request
							response = httpclient.execute(httppost);
							Reader in = new BufferedReader(
							        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
							    //builder1= new StringBuilder();
							    char[] buf = new char[1000];
							    int l = 0;
							    while (l >= 0) {
							        builder1.append(buf, 0, l);
							        l = in.read(buf);
							    }
							System.out.println("Response ->"+builder1.toString());

						} catch (ClientProtocolException e) {
							System.out.println("exception 1");
							// TODO Auto-generated catch block
						} catch (IOException e) {
							e.printStackTrace();
							System.out.println("error ");
							// TODO Auto-generated catch block
						}
						if(builder1.toString().equals("Silent"))
						{
							AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
						}
						else if(builder1.toString().equals("Vibrate"))
						{
							AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
						}
						else if(builder1.toString().equals("Voicemail"))
						{
							try{
								TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
								Class c = Class.forName(manager.getClass().getName());
								Method m = c.getDeclaredMethod("getITelephony");
								m.setAccessible(true);
								ITelephony telephony = (ITelephony)m.invoke(manager);
								telephony.endCall();
							} catch(Exception e){
								e.printStackTrace();
							}
						}

					}
					else   // if current event time is not satisfied
					{
						if(currentDate.after(GlobalData.currentRuleendTime))  // if time of previous event is done then change to ringtone
						{
							AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
							am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
						}
					}
				}while (eventCursor.moveToNext());
			}
		}
	}*/
}



